<template>
  <header class="fixed right-0 top-0 z-[1000] w-full bg-[#2a3032] lg:shadow-black/50 shadow-2xl">
    <div class="flex h-12 items-center justify-between bg-[#2a3032] px-3 lg:px-1 lg:mx-auto lg:h-[80px] lg:w-100">
      <div class="relative hidden lg:flex">
        <!--       大屏 logo-->
        <nuxt-link :to="$localePath('/')" external>
          <WImage
            alt="BitTopup Logo"
            class="mr-5 w-[130px]"
            width="130"
            height="46"
            :src="useAsset('logo/logo@2x.png')" />
        </nuxt-link>
        <!--     大屏才显示的分类-->
        <div class="relative flex items-center">
          <nuxt-link
            external
            :to="$localePath(`/category/${item.id}/1`)"
            class="mr-5 flex items-center hover:bg-[rgba(255,255,255,.08)] p-3 py-1.5 duration-200 rounded-2xl"
            v-for="(item, index) in categoryTree"
            :key="index">
            <span class="ltr:mr-2.5 rtl:ml-2.5 text-xs font-[600] text-[#fff] uppercase">
              {{ item.categoryName }}
            </span>
            <div
              class="rounded-full p-1 hover:bg-red1 duration-200 cursor-pointer shrink-0"
              @click.prevent="showCategoryList(item, index)">
              <WImage class="h-3 w-3" :src="useAsset('xia.png')" />
            </div>
          </nuxt-link>
          <!--    大屏顶部分类点击  弹窗展示子分类-->
          <div
            v-if="modalIsActive"
            ref="modalElRef"
            class="absolute modal-animation shadow-lg shadow-gray-dark -left-4 top-12 flex min-h-[150px] w-[420px] flex-wrap items-start justify-between rounded-lg bg-[#31383b] p-5">
            <NuxtLink
              external
              class="mb-2.5 flex w-[48%] items-center"
              v-for="(item, idx) in currentCategory.subCategories"
              :to="$localePath(`/category/${currentCategoryId}/${item.id}/1`)"
              :key="idx">
              <w-image class="mr-3 h-5 w-5 object-contain object-center" height="25" :src="getCategoryIcon(item.id)" />
              <span class="text-white text-base font-light line-clamp-1">{{ item.categoryName }}</span>
            </NuxtLink>
          </div>
        </div>
      </div>
      <div class="flex lg:hidden shrink-0 items-center">
        <!-- 小屏 logo -->
        <nuxt-link class="w-8 h-8 ltr:mr-3 rtl:ml-3 shrink-0" :to="$localePath('/')" external>
          <WImage alt="BitTopup Logo" width="30" height="30" :src="useAsset('logo/icon-logo@2x.png')" />
        </nuxt-link>
        <!-- 分类菜单 按钮 -->
        <WImage @click="openCategory" class="h-6 w-6" :src="useAsset('ego-menu.png')" />
      </div>
      <!--      右侧-->
      <div class="flex flex-1 items-center justify-between">
        <!--        小屏搜索框-->
        <div
          class="w-[95px] mx-auto h-7 rounded-md bg-[#1f1e1e] lg:hidden flex align-center px-2 py-0.5"
          @click="$pushRoute('/common/search')">
          <span class="text-gray-light text-sm">{{ $mt('Search') }}</span>
          <!--          <WImage class="ltr:ml-auto rtl:mr-auto w-5" :src="useAsset('pc-home/h5header_search.png')" />-->
        </div>
        <!--        大屏搜索框-->
        <div
          class="mr-5 hidden items-center focus-within:border-red1 focus-within:shadow-md duration-200 focus-within:shadow-[rgba(255,0,0,0.4)] border-[2px] border-transparent justify-between rounded-3xl bg-[#353b3c] px-2.5 py-1 lg:flex">
          <input
            v-model="searchKeywords"
            @keydown.enter="$pushRoute({ path: '/common/search', query: { keywords: searchKeywords } })"
            class="w-[60%] pl-2 bg-transparent text-white text-sm py-1"
            :placeholder="$mt('Search')" />
          <van-icon
            @click="$pushRoute({ path: '/common/search', query: { keywords: searchKeywords } })"
            class="cursor-pointer"
            name="search"
            size="20px"
            color="#fff" />
        </div>
        <!--    语言和登录-->
        <div class="lg:min-w-[300px] min-w-[150px] justify-end whitespace-nowrap px-1 py-2 flex lg:items-center">
          <client-only>
            <template #fallback>
              <div class="w-full h-6 bg-[rgba(0,0,0,.5)] rounded anime-progress"></div>
            </template>
            <!--        lang-->
            <NuxtLink
              external
              :to="
                $localePath(
                  $localePath(route.path, 'en') === '/'
                    ? '/common/lang'
                    : `/common/lang?redirectTo=${encodeURIComponent(route.fullPath)}`,
                )
              "
              class="flex items-center text-sm mr-3 lg:mr-5 text-white">
              <div class="flex items-center">
                <span class="shrink-0">{{ langName }}</span>
                <span class="mx-1 text-[#5c5a5af0]">/</span>
                <span class="shrink-0 whitespace-nowrap" v-if="curCurrency.name">{{ curCurrency.name || '-' }}</span>
                <van-loading class="ml-2" :size="16" v-else />
              </div>
            </NuxtLink>

            <aside class="shrink-0">
              <!--         小屏 -->
              <div>
                <!--                已登录-->
                <div v-if="isLogin" class="lg:hidden" @click="showH5LoginDialog = true">
                  <img
                    v-if="memberInfo.avatar"
                    class="h-6 w-6 rounded-[50%] cursor-pointer"
                    alt="customer avatar"
                    width="24px"
                    height="24px"
                    :src="$withPicOrigin(memberInfo.avatar)" />
                  <div
                    v-else
                    class="ltr:ml-2 rtl:mr-2 flex h-6 w-6 items-center justify-center rounded-[50%] bg-[#fff]">
                    <WImage alt="avatar" class="h-4 w-4" :src="useAsset('wodefill.png')" />
                  </div>
                </div>
                <!--                未登录-->
                <div
                  v-else
                  @click="showH5LoginDialog = true"
                  class="ltr:ml-2 rtl:mr-2 flex h-6 w-6 items-center justify-center rounded-[50%] bg-[#fff] lg:hidden">
                  <WImage alt="avatar" class="h-4 w-4" :src="useAsset('wodefill.png')" />
                </div>
              </div>
              <!--       已登录   大屏-->
              <div v-if="isLogin" @click="openAccount" class="hidden lg:ml-5 cursor-pointer lg:flex items-center">
                <span class="text-white whitespace-nowrap shrink-0 mr-3">{{ memberInfo.email }}</span>
                <img
                  v-if="memberInfo.avatar"
                  class="rounded-[50%] shrink-0"
                  width="30px"
                  height="30px"
                  alt="customer avatar"
                  :src="$withPicOrigin(memberInfo.avatar)" />
                <div
                  v-else
                  class="cursor-pointer flex ml-5 mr-3 h-8 w-8 shrink-0 items-center justify-center rounded-[50%] bg-[#fff]">
                  <div class="flex h-5 w-5 items-center justify-center rounded-[50%] bg-[#545b64]">
                    <van-icon name="user" />
                  </div>
                </div>
              </div>
              <!--       未登录   大屏-->
              <div
                v-else
                @click="showPcLoginDialog = true"
                class="whitespace-nowrap items-center hidden lg:flex cursor-pointer">
                <span class="text-base text-red1">
                  {{ $mt('Sign in') }}
                  <span class="mx-1 text-[#5c5a5af0]">/</span>
                  {{ $mt('Sign up') }}
                </span>
              </div>
            </aside>
          </client-only>
        </div>
      </div>
    </div>
  </header>
  <PopupLeft :categoryList="categoryTree" v-model="showLeft" />
  <LoginRightPopup class="lg:hidden" v-model="showH5LoginDialog" />
  <LoginRightDialog class="hidden login-dialog lg:block" v-model="showPcLoginDialog" />
</template>

<script setup lang="ts">
import { useAsset } from '~/utils'
import WImage from '~/components/logic/WImage.vue'
import PopupLeft from '~/components/category/PopupLeft.vue'
import { useRequest } from '~/composables/useRequest'
import { useMemberStore } from '~/store/member'
import { useCategoryStore } from '~/store/category'
import { useMetaStore } from '~/store/meta'

const { $isPcScreen, getCurrentLangCode, $localePath } = useCommonPlugin()
const route = useRoute()
const langCookie = useCookie('i18n_redirected', { path: '/', default: () => 'en' })
const searchKeywords = ref('')
const modalElRef = ref()
onClickOutside(modalElRef, (event) => (modalIsActive.value = false))
const CategoryStore = useCategoryStore()
const { categoryTree } = storeToRefs(CategoryStore)
const {
  public: { LANGUAGES: langList },
} = useRuntimeConfig()
const metaStore = useMetaStore()
const { curCurrency } = storeToRefs(metaStore)
// 获取所有货币，展示当前货币
const memberStore = useMemberStore()
const { memberInfo, isLogin } = storeToRefs(memberStore)
const showLeft = ref(false)
const showH5LoginDialog = ref(false)
const showPcLoginDialog = ref(false)
const currentCategory = ref({})
const modalIsActive = ref(false)
const currentCategoryId = ref()
const currentCategoryName = ref('')
// ----------------
const { requestGet, requestPost } = useRequest()
const langName = computed(() => langList.find((item) => item.code === langCookie.value)?.label)
const openAccount = () => {
  if ($isPcScreen()) showPcLoginDialog.value = true
  else showH5LoginDialog.value = true
}
const openCategory = () => {
  showLeft.value = true
}

const showCategoryList = ({ id, categoryName }, index: number) => {
  currentCategoryId.value = id
  currentCategory.value = categoryTree.value.find((item) => item.id === id)
  modalIsActive.value = true
  currentCategoryName.value = categoryName
}
const categories = categoryTree.value.map((item) => item.subCategories).flat(Infinity) || []
const getCategoryIcon = (id) => {
  return useAsset(`goods-icons/${categories.findIndex((item) => item.id === id) % 20}`)
}

onMounted(() => {
  langCookie.value = getCurrentLangCode(route)
})
</script>

<style lang="scss">
.login-dialog .van-popup--center {
  top: 220px;
  right: 100px;
  left: unset;
}

@keyframes modal-fade-in {
  from {
    transform: translateY(-15px);
    opacity: 0;
  }
}

@keyframes anime-progress {
  from {
    opacity: 0.2;
  }
}

.modal-animation {
  animation: modal-fade-in 0.3s;
}

.anime-progress {
  animation: anime-progress 1s infinite alternate;
}
</style>
